import React, { PureComponent } from 'react'
import { Form, Row, Col, Input, Button, Icon, Select, DatePicker, InputNumber } from 'antd'
import moment from 'moment'
import * as R from 'ramda'
// import store from '../../../index'
import { transferOption, isNotEmptyAndNil } from '@/utils/common'
import styles from './index.less'

// const { dispatch } = store; // todo: dispatch
const { RangePicker } = DatePicker;
const FormItem = Form.Item;
const dateFormat = 'YYYY-MM-DD HH:mm:ss';

// @Form.create()
export default class PateoSearchFormExpand extends PureComponent {

  state = {
    expandForm: false,
  };

  handleSearch = e => {
    e.preventDefault();
    const { form: { validateFields }, fetchUrl, payloadUrl, saveFormValues, dateFormatList, dateFormatListNoTime, handleRangePicker } = this.props;
    validateFields((err, fieldsValue) => {
      if (err) return;

      for (let para in fieldsValue) {
        if (!fieldsValue[para] || !fieldsValue[para].toString().trim()) {
          fieldsValue[para] = undefined
        }
      }

      if (handleRangePicker) {
        const rangePicker = handleRangePicker(fieldsValue);
        if (isNotEmptyAndNil(rangePicker)) return
      }

      // dateFormatList:是用来格式化时间的
      if (dateFormatList) {
        dateFormatList.map(title => fieldsValue[title] ?
          (fieldsValue[title] = moment(fieldsValue[title]).format('YYYY-MM-DD HH:mm:ss')) : (fieldsValue[title] = undefined))
      }

      // dateFormatListNoTime:是用来格式化日期的
      if (dateFormatListNoTime) {
        dateFormatListNoTime.map(title => fieldsValue[title] ?
          (fieldsValue[title] = moment(fieldsValue[title]).format('YYYY-MM-DD')) : (fieldsValue[title] = undefined))
      }

      // saveFormValues:子组件向父组件传递表单的数据 和 dateFormatList 的顺序不可颠倒。
      if (saveFormValues) saveFormValues(fieldsValue);
      dispatch({
        type: fetchUrl,
        payload: payloadUrl ? Object.assign(payloadUrl, fieldsValue) : fieldsValue,
      })
    })
  }

  handleFormReset = () => {
    const { form, fetchUrl, payloadUrl, handleFormReset, customHandleFormReset } = this.props;
    form.resetFields();
    if(customHandleFormReset){
      customHandleFormReset();
      return;
    }
    if (handleFormReset) { handleFormReset() }
    dispatch({
      type: fetchUrl,
      payload: payloadUrl || {},
    })
  }

  renderForm = () => {
    const { searchItems = [], isExpand } = this.props;
    const loopFormItems = data => data.map((item, i) => {
      if (!this.state.expandForm && isExpand && i > 1) {
        return null;
      }
      const { title, key, type, max = Infinity } = item
      switch (type) {
        case 'input': {
          const placeholder = `请输入${typeof (title) === 'string' ? title : ''}`;
          return (
            <Col md={8} sm={24} key={key}>
              <FormItem
                key={key}
                label={title}
                name={key}
              >
                <Input placeholder={placeholder} autoComplete='off' allowClear maxLength={max}/>
              </FormItem>
            </Col>
          )
        }
        case 'inputNumber': {
          const { min, max, precision, holder } = item;
          const placeholder = `请输入${typeof (title) === 'string' ? title : ''}`;
          return (
            <Col md={8} sm={24} key={key}>
              <FormItem
                key={key}
                label={title}
                name={key}
              >
                <InputNumber placeholder={holder ? holder : placeholder} min={min} max={max} precision={precision} style={{ width: '100%' }} />
              </FormItem>
            </Col>
          )
        }
        case 'select': {
          const { selectOptions, keyValue, onSelectChange, initialValue, cantClear, mode, placeholder, optionLabelProp, onSearch, onSelect } = item;
          const options = { initialValue }
          return (
            <Col md={8} sm={24} key={key}>
              <FormItem key={key} label={title} name={key} {...options}>
                <Select
                  placeholder={placeholder ? placeholder : '请选择'}
                  showSearch
                  optionFilterProp="children"
                  allowClear={!cantClear}
                  onChange={onSelectChange}
                  //getPopupContainer={triggerNode => triggerNode.parentNode}
                  getPopupContainer={() => document.getElementById("public")}
                  mode={mode}
                  optionLabelProp={optionLabelProp}
                  onSearch={onSearch}
                  onSelect={onSelect}
                >
                  {transferOption(selectOptions, keyValue)}
                </Select>
              </FormItem>
            </Col>
          )
        }
        case 'datePicker': {
          const { nohmsFormat, noTimeSelect } = item;
          return (
            <Col md={8} sm={24} key={key}>
              <FormItem key={key} label={title} name={key}>
                <DatePicker
                  showTime={!noTimeSelect}
                  format={nohmsFormat ? nohmsFormat : dateFormat}
                  showToday
                  getCalendarContainer={trigger => trigger.parentNode}
                />
              </FormItem>
            </Col>
          )
        }
        case 'rangePicker': {
          // 这里不再推荐使用noTimeSelect,showTime,
          const { nohmsFormat, noTimeSelect, specialStyle, disabledDate, disabledTime, showTime, style, dateRender } = item;
          return (
            <Col md={specialStyle || 8} sm={24} key={key}>
              <FormItem key={key} label={title} name={key}>
                <RangePicker
                  style={style}
                  disabledDate={disabledDate}
                  disabledTime={disabledTime}
                  showTime={R.isNil(showTime) ? !noTimeSelect : showTime}
                  format={nohmsFormat ? nohmsFormat : dateFormat}
                  placeholder={['开始时间', '结束时间']}
                  ranges={{
                    '本周 ': [moment().startOf('weeks'), moment()],
                    '最近一周 ': [moment().add(-1, 'weeks'), moment()],
                    '本月 ': [moment().startOf('months'), moment()],
                    '最近一个月 ': [moment().add(-1, 'months'), moment()],
                  }}
                  dateRender={dateRender}
                  getCalendarContainer={trigger => trigger.parentNode}
                />
              </FormItem>
            </Col>
          )
        }
        //这个是用来调整格式的
        case 'blank': {
          return (
            <Col md={8} sm={24} key={key}>
              <FormItem key={key}>
              </FormItem>
            </Col>
          )
        }
      }
    })
    return loopFormItems(searchItems)
  }

  render() {
    const { searchItems = [], isExpand, searchSpan = 8, isQueryAuth = true } = this.props;
    const { expandForm } = this.state;
    const offset =
      isExpand ?
        (searchItems.length <= 2
          ? 16 - (searchItems.length % 3) * 8
          : expandForm
            ? 16 - (searchItems.length % 3) * 8
            : 0) : 16 - (searchItems.length % 3) * 8;
    return (
      <div className={styles.tableListForm} id={"public"}>
        <Form onSubmit={this.handleSearch} layout='inline' ref="form">
          <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
            {this.renderForm()}
            {isQueryAuth ? (
              <Col span={searchSpan} offset={offset}>
              <span className={styles.expendButtons}>
                <Button type='primary' htmlType='submit'>查询</Button>
                <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
                {
                  this.props.searchItems.length > 2 && this.props.isExpand ? (
                    <a
                      style={{ marginLeft: 8 }}
                      onClick={() => this.setState({ expandForm: !this.state.expandForm })}
                    >
                      {!this.state.expandForm ? <span>展开 <Icon type="down" /></span> : <span>收起 <Icon type="up" /></span>}
                    </a>
                  ) : null
                }
              </span>
            </Col>
            ) : null}
            
          </Row>
        </Form>
      </div>
    )
  }
}

